#!/bin/bash
# 版本1.4 - 支持协议选择

handle_error() {
    echo "错误: $1" >&2
    echo "阶段: $2" >&2
    exit 1
}

configure_safety() {
    if ! git config --global --get-all safe.directory | grep -q "^${project_dir}$"; then
        echo "▶ 正在配置Git安全目录..."
        if ! git config --global --add safe.directory "${project_dir}"; then
            echo "⚠ 请手动执行以下命令解决权限问题："
            echo "   sudo git config --system --add safe.directory '${project_dir}'"
        fi
    fi
}

# 协议选择函数
select_protocol() {
    while true; do
        read -p "选择协议类型 (http/https) [默认https]: " protocol
        protocol=${protocol:-https}
        case $protocol in
            http|https) break ;;
            *) echo "无效协议，请输入 http 或 https" ;;
        esac
    done
}

# 输入验证
validate_input() {
    [[ "$1" =~ ^[a-zA-Z0-9_-]+$ ]] || handle_error "输入包含非法字符" "输入验证"
}

# 主流程
command -v git >/dev/null 2>&1 || handle_error "请先安装git：\nsudo apt install git -y" "依赖检查"

read -p "项目目录绝对路径 [默认当前目录]: " project_dir
project_dir=${project_dir:-$(pwd)}
[ -d "$project_dir" ] || handle_error "目录不存在" "目录检查"
cd "$project_dir" || handle_error "无法进入目录" "目录访问"
configure_safety

select_protocol

read -p "GitLab群组名称: " group_name
validate_input "$group_name"

read -p "仓库名称: " repo_name
validate_input "$repo_name"

read -p "目标分支 [默认main]: " branch
branch=${branch:-main}

# 令牌验证
while true; do
    read -s -p "GitLab访问令牌 (需api权限): " access_token
    echo
    if [[ $access_token =~ ^glpat-[a-zA-Z0-9_-]{20}$ ]]; then
        break
    else
        echo "无效令牌格式，正确格式：glpat-开头+20位字符"
    fi
done

# 构建远程URL
if [ "$protocol" = "https" ]; then
    remote_url="https://oauth2:${access_token}@gitlab.uoto.fun/${group_name}/${repo_name}.git"
else
    remote_url="http://${access_token}@gitlab.uoto.fun/${group_name}/${repo_name}.git"
fi

# 仓库初始化
if [ ! -d .git ]; then
    git init || handle_error "初始化失败" "git init"
    echo "✔ 初始化Git仓库完成"
fi

# 配置远程
if git remote | grep -q origin; then
    git remote set-url origin "$remote_url" || handle_error "更新远程失败" "git remote"
else
    git remote add origin "$remote_url" || handle_error "添加远程失败" "git remote"
fi

# 提交推送
echo "▶ 正在提交代码到${protocol^^}仓库..."
git add . && \
git commit -m "自动提交 $(date +'%Y-%m-%d %H:%M:%S')" && \
git push -u origin "$branch" || handle_error "推送失败" "git操作"

echo "✅ 代码已通过${protocol^^}协议推送至 ${group_name}/${repo_name}"
